package com.haoran.dwz.controller;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import com.haoran.dwz.common.DisorderedCompressEncoder;
import com.haoran.dwz.domain.ShortURL;
import com.haoran.dwz.repository.ShortURLRepository;

@Controller
public class DwzController {

	@Autowired
	private ShortURLRepository shortURLRepository;

	/**
	 * @param response
	 * @param id 64进制
	 */
	@GetMapping(value = "{id}")
	public ResponseEntity<String> parseAndRedirect(HttpServletResponse response, @PathVariable String id) {
		try {
			long unCompressNumber = DisorderedCompressEncoder.unCompressNumber(id);
			if (shortURLRepository.exists(unCompressNumber)) {
				ShortURL shortURL = shortURLRepository.findOne(unCompressNumber);
				shortURL.setLastUsedTime(now());
				shortURL.setExpireTime(oneYearLater());
				ShortURL save = shortURLRepository.save(shortURL);
				String url = save.getUrl();
				response.sendRedirect(url);
				return ResponseEntity.ok().build();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return ResponseEntity.notFound().build();
	}

	private Date now() {
		Calendar instance = Calendar.getInstance();
		return instance.getTime();
	}

	private Date oneYearLater() {
		Calendar instance = Calendar.getInstance();
		instance.add(Calendar.YEAR, 1);
		return instance.getTime();
	}
}
